package com.sky.service.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.common.SetmealDishMapper;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate  redisTemplate;
    /**
     * 新增菜品和对应的口味数据
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //创建菜品对象
        Dish dish = new Dish();
        //拷贝
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入一条数据
        dishMapper.insert(dish);//后续步骤实现
        //获取插入后的菜品的id
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);//后续步骤实现
        }
        clearCache("dish:categoryId:*");
    }
    /**
     * 删除redis缓存方法
     */
    public void clearCache(String keyPattern){
        Set keys = redisTemplate.keys(keyPattern);
        keys.forEach(key->{
            redisTemplate.delete( key);
        });
    }
    /**
     *
     * @param dishPageQueryDTO
     * @return
     */

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //开启分页设置
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);//后续步骤实现
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional//多变删除添加事务
    public void deleteBatch(List<Long> ids) {
        //1.先判断删除的菜品中是否存在起售的
        Integer count = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if(count > 0){
            //在售中，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //2.判断删除的菜品中是否有被套餐引用的
        Integer count2 = setmealDishMapper.selectCountByDishIds(ids);
        if(count2 > 0){
            //有关联套餐，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.删除dish表的数据
        dishFlavorMapper.deleteByDishIds(ids);

        //4.删除dishFlavor表的数据
        dishMapper.deleteByIds(ids);
        clearCache("dish:categoryId:*");
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //调用dishMapper查询菜品数据
        DishVO dishVO = dishMapper.selectById(id);
        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //1.修改dish表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        //2.修改dish_flavor表(对于关系表的修改操作)
        //a.删除中间表的数据
        dishFlavorMapper.deleteByDishId(dish.getId());
        //b.再添加中间表数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.batchSave(flavors);
        clearCache("dish:categoryId:*");
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //1.查询菜品缓存
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get("dish:categoryId:" + dish.getCategoryId());
        //2.缓存存在，直接返回
        if(dishVOList != null && dishVOList.size() > 0){
            return dishVOList;
        }
        List<Dish> dishList = dishMapper.list(dish);
        dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        redisTemplate.opsForValue().set("dish:categoryId:" + dish.getCategoryId(), dishList);
        return dishVOList;
    }
}
